// +build windows

package utils

import (
	"errors"

	"context" //"golang.org/x/net/context"
	//_ "github.com/go-sql-driver/mysql"
	"os/exec"
	"strconv"
	"syscall"
)

type Result struct {
	output string
	err    error
}

// 执行shell命令，可设置执行超时时间
func ExecShell(ctx context.Context, command string) (string, error) {
	cmd := exec.Command("cmd", "/C", command)
	// 隐藏cmd窗口
	cmd.SysProcAttr = &syscall.SysProcAttr{
		HideWindow: true,
	}
	var resultChan chan Result = make(chan Result)
	go func() {
		output, err := cmd.CombinedOutput()
		resultChan <- Result{string(output), err}
	}()
	select {
	case <-ctx.Done():
		if cmd.Process.Pid > 0 {
			exec.Command("taskkill", "/F", "/T", "/PID", strconv.Itoa(cmd.Process.Pid)).Run()
			cmd.Process.Kill()
		}
		return "", errors.New("timeout killed")
	case result := <-resultChan:
		return ConvertEncoding(result.output), result.err
	}
}

func ConvertEncoding(outputGBK string) string {
	// windows平台编码为gbk，需转换为utf8才能入库
	outputUTF8, ok := GBK2UTF8(outputGBK)
	if ok {
		return outputUTF8
	}

	return outputGBK
}

// 获取数据库引擎DSN  mysql,sqlite,postgres
//func getDbEngineDSN(req *pb.DbTaskRequest) string {
//engine := strings.ToLower(setting.Db.Engine)
//dsn := ""
//if req.Dtype == utils.SqlsT {
//	//dsn = fmt.Sprintf("user=%s password=%s host=%s port=%d dbname=%s sslmode=disable",
//	var dataSource string
//	if req.Port != 0 {
//		strInt64 := strconv.FormatInt(req.Port, 10)
//		id16, _ := strconv.Atoi(strInt64)
//		dataSource = req.Dip + "," + strconv.Itoa(id16) //setting.Db.Host
//	} else {
//		dataSource = req.Dip
//	}
//	db := Mssql{
//		DataSource: dataSource,
//		Database:   req.Dbname,
//		// windwos: true 为windows身份验证，false 必须设置sa账号和密码
//		Windows: false,
//		Sa: SA{
//			User:   req.Ac,
//			Passwd: req.Pd,
//		},
//	}
//	dsn = utils.GetDsn()
//}
//
//return dsn
//}
